<script setup lang="ts">
/**
 * 东营旅游路线规划App客户端 - 主页面组件
 *
 * 该组件是应用的主界面，集成了地图显示、景点查询、路线规划和导航功能。
 * 使用ArcGIS API实现地图功能，Capacitor提供设备原生功能访问。
 */

// Vue核心功能导入
import { ref } from 'vue'
import { onMounted } from 'vue'

// ArcGIS地图相关组件导入
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import Handles from '@arcgis/core/core/Handles.js'
import FeatureLayerView from '@arcgis/core/views/Layers/FeatureLayerView.js'
import Graphic from '@arcgis/core/Graphic'
import FeatureSet from '@arcgis/core/rest/support/FeatureSet.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import Point from '@arcgis/core/geometry/Point.js'
import Polyline from '@arcgis/core/geometry/Polyline.js'
import SimpleRenderer from "@arcgis/core/renderers/SimpleRenderer.js"
import SimpleMarkerSymbol from "@arcgis/core/symbols/SimpleMarkerSymbol.js";
import SimpleFillSymbol from '@arcgis/core/symbols/SimpleFillSymbol';

// Ionic UI组件导入
import {
  IonPage, IonItem, IonIcon, IonLabel, IonModal, IonImg, IonList,
  IonContent, IonCard, IonCardContent, IonNote, IonCardTitle,
  IonCardHeader, IonButtons, IonButton, IonHeader, IonToolbar,
  IonTitle, IonItemDivider, IonInput,
} from '@ionic/vue'

// Ionic图标导入
import {
  locationOutline, eyeOutline, gitNetworkOutline, cropOutline,
  moonOutline, listOutline, imageOutline, closeOutline,
  compassOutline, filterOutline, chevronDownOutline, speedometerOutline
} from 'ionicons/icons'

// Capacitor原生功能导入
import { Geolocation } from '@capacitor/geolocation'
import { Capacitor } from '@capacitor/core'

// 自定义工具和API导入
import gaodeLayer from '@/utils/GaoDeBaseLayer' // 高德地图底图
import { createFeatureLayer } from '@/utils/public'
import { Toast } from '@/utils/toast' // 自定义Toast提示
import { getAmapWeather } from '@/utils/weather' // 高德天气API
import { getGaoDeRoute } from '@/utils/gaodeAPI' // 高德路径规划API
import performanceTest from '@/utils/PerformanceTest' // 性能测试工具

// 类型定义导入
import { AreaType, RoadType, SpotType } from '@/types/public'


/**
 * 地图图层和容器初始化
 */
// 添加临时图层用于存储路线
const tempGraphicLayer: GraphicsLayer = new GraphicsLayer()

// 初始化地图容器
const mapViewContainer = ref<HTMLDivElement>() // 地图DOM容器引用

/**
 * UI状态控制变量
 */
const DetailDrawer = ref(false) // 景点详情抽屉的显示状态
const spotData = ref<SpotType | null>(null) // 当前选中的景点数据
const roadData = ref<RoadType | null>(null) // 当前选中的景点道路数据
const areaData = ref<AreaType | null>(null) // 当前选中的景点区域数据
const multiSelect = ref(false) // 是否处于多选模式
const multiSelectTableData = ref<SpotType[] | RoadType[] | AreaType[]>([]) // 多选景点数据列表
const searchText = ref('') // 搜索文本输入

/**
 * 景点类型筛选相关变量
 */
const showTypeFilter = ref(false) // 是否显示类型筛选弹窗
const selectedSpotType = ref<string>('') // 当前选中的景点类型
const filteredSpots = ref<SpotType[]>([]) // 按类型筛选后的景点列表
const spotTypes = ['游玩', '文化', '度假', '其他'] // 支持的景点类型列表

/**
 * 地图交互相关变量
 */
let clickHandler: IHandle | null = null // 地图点击事件处理器
let clickQueryResult: FeatureSet | null = null // 点击查询结果集
const highlightHandle: Handles = new Handles() // 高亮显示要素的句柄
let detailTitle: string | null = null // 详情弹窗标题
let dataDrawerType: string | null = null // 当前数据类型(spot/road/area)

/**
 * 位置跟踪相关变量
 */
const isTracking = ref(false) // 是否正在进行位置跟踪
let watchId: string | null = null // 位置监听器ID
let locationGraphic: Graphic | null = null // 位置图标

/**
 * 天气信息相关变量
 */
const weatherData = ref<any>(null) // 天气数据
const weatherError = ref<string | null>(null) // 天气错误信息

/**
 * 定义景点图层 - 使用点符号表示景点位置
 * 从ArcGIS Online Feature Service加载景点数据
 */
const spotLayer = new FeatureLayer({
  url: 'https://services5.arcgis.com/QHJE36ge0b3AlcS2/arcgis/rest/services/szwhy_dianxianmian/FeatureServer/0',
  outFields: ['*'], // 获取所有字段
  renderer: new SimpleRenderer({
    symbol: new SimpleMarkerSymbol({
      color: [255, 0, 0, 0.8], // 鲜红色(#FF0000)，透明度为0.8，用于突出显示景点位置
      size: 8, // 点大小
      outline: {
        color: [0, 0, 0, 1], // 纯黑色(#000000)边框，不透明，增强可见性
        width: 1 // 边框宽度
      }
    })
  })
});

/**
 * 定义道路图层 - 使用线符号表示景点间的路线
 * 从ArcGIS Online Feature Service加载道路数据
 */
const roadLayer = new FeatureLayer({
  url: 'https://services5.arcgis.com/QHJE36ge0b3AlcS2/arcgis/rest/services/szwhy_dianxianmian/FeatureServer/1',
  outFields: ['*'], // 获取所有字段
  renderer: new SimpleRenderer({
    symbol: new SimpleLineSymbol({
      color: [171, 68, 68, 0.8], // 砖红色(#AB4444)，透明度为0.8，用于表示连接景点的道路
      width: 3, // 线宽
    })
  })
});

/**
 * 定义区域图层 - 使用面符号表示景区范围
 * 从ArcGIS Online Feature Service加载区域数据
 */
const areaLayer = new FeatureLayer({
  url: 'https://services5.arcgis.com/QHJE36ge0b3AlcS2/arcgis/rest/services/szwhy_dianxianmian/FeatureServer/2',
  outFields: ['*'], // 获取所有字段
  renderer: new SimpleRenderer({
    symbol: new SimpleFillSymbol({
      color: [255, 255, 0, 0.2], // 明黄色(#FFFF00)，透明度为0.2，用于表示景区范围，低透明度便于查看底图
      outline: {
        color: [0, 0, 0, 1], // 纯黑色(#000000)边框，不透明，清晰界定区域边界
        width: 1 // 边框宽度
      }
    })
  })
});

/**
 * 初始化地图对象
 * 使用高德地图作为底图
 */
const map = new Map({
  basemap: {
    baseLayers: [gaodeLayer], // 使用从GaoDeBaseLayer导入的高德地图图层
  },
});

// 将所有图层添加到地图中
map.addMany([spotLayer, roadLayer, areaLayer, tempGraphicLayer]);

/**
 * 初始化地图视图
 * 设置初始中心点为东营市广饶县位置
 */
const view = new MapView({
  map: map,
  center: [118.45786183624148, 37.04540349081432], // 经度，纬度
  zoom: 18, // 初始缩放级别
});

/**
 * 高亮显示地图要素
 *
 * @param layer - 要素所在的图层
 * @param feature - 要高亮显示的要素
 */
const highlightFeature = async (layer: FeatureLayer, feature: Graphic) => {
  // 获取图层视图
  const featureLayerView = (await view.whenLayerView(layer)) as FeatureLayerView
  // 创建高亮效果
  const highlight = featureLayerView.highlight(feature)
  // 将高亮句柄添加到管理器中，便于后续清除
  highlightHandle.add(highlight)
}

/**
 * 处理地图点击查询要素
 * 实现点击地图查询并显示要素详情的功能
 *
 * @param layer - 要查询的图层
 * @param featureType - 要素类型名称('景点'|'道路'|'区域')
 */
const handleClickToEditFeature = async (layer: FeatureLayer, featureType: '景点' | '道路' | '区域') => {
  // 注册地图点击事件
  clickHandler = view.on('click', async function (event) {
    // 创建性能计时器名称
    const timerName = `query${featureType}`;
    // 开始性能计时
    performanceTest.startTimer(timerName, { featureType });
    // 获取点击位置
    const mapPoint = event.mapPoint.clone()

    // 构建空间查询参数
    const query = new Query()
    query.geometry = mapPoint // 查询点
    query.distance = 3 // 缓冲距离
    query.units = 'meters' // 距离单位
    query.spatialRelationship = 'intersects' // 空间关系为相交
    query.returnGeometry = true // 返回几何信息
    query.outFields = ['*'] // 返回所有字段

    // 执行空间查询
    clickQueryResult = await layer.queryFeatures(query)
    detailTitle = `该区域存在多个${featureType}，请选择具体的一个${featureType}，我们将为您展示它的详细信息`

    // 处理查询结果
    if (clickQueryResult.features.length > 0) {
      // 查询成功后移除点击事件，防止重复触发
      clickHandler?.remove()
      clickHandler = null

      // 如果找到多个要素，显示选择列表
      if (clickQueryResult.features.length > 1) {
        multiSelect.value = true // 激活多选模式

        // 根据要素类型设置多选数据
        if (featureType === '景点') {
          multiSelectTableData.value = clickQueryResult.features.map((feature) => feature.attributes as SpotType)
        } else if (featureType === '道路') {
          multiSelectTableData.value = clickQueryResult.features.map((feature) => feature.attributes as RoadType)
        } else if (featureType === '区域') {
          multiSelectTableData.value = clickQueryResult.features.map((feature) => feature.attributes as AreaType)
        }
      } else {
        // 只有一个要素时直接显示详情
        highlightFeature(layer, clickQueryResult.features[0]) // 高亮显示要素

        // 根据要素类型设置详情数据
        if (featureType === '景点') {
          spotData.value = clickQueryResult.features[0].attributes as SpotType
        } else if (featureType === '道路') {
          roadData.value = clickQueryResult.features[0].attributes as RoadType
        } else if (featureType === '区域') {
          areaData.value = clickQueryResult.features[0].attributes as AreaType
        }

        // 显示详情抽屉
        DetailDrawer.value = true

        // 记录性能数据 - 单个结果
        performanceTest.endTimer(timerName, { success: true, featuresCount: 1 });
      }
    } else {
      // 未找到要素时提示用户
      Toast.info(`未找到对应的${featureType}`)

      // 记录性能数据 - 无结果
      performanceTest.endTimer(timerName, { success: true, featuresCount: 0 });
    }
  })
}

/**
 * 搜索景点、路线或区域功能
 * 允许用户通过点击地图查询不同类型的要素
 *
 * @param type - 要搜索的要素类型('spot'|'road'|'area')
 */
const searchScenic = (type: 'spot' | 'road' | 'area') => {
  // 清除之前的高亮显示，避免视觉干扰
  highlightHandle.removeAll()

  if (type === 'spot') {
    // 搜索景点
    dataDrawerType = 'spot' // 设置当前数据类型为景点
    Toast.info('请点击地图上的景点，我们将为您展示它的详细信息') // 用户提示
    handleClickToEditFeature(spotLayer, '景点') // 注册点击事件处理器
  } else if (type === 'road') {
    // 搜索路线
    dataDrawerType = 'road' // 设置当前数据类型为路线
    Toast.info('请点击地图上的路线，我们将为您展示它的详细信息') // 用户提示
    handleClickToEditFeature(roadLayer, '道路') // 注册点击事件处理器
  } else if (type === 'area') {
    // 搜索区域
    dataDrawerType = 'area' // 设置当前数据类型为区域
    Toast.info('请点击地图上的区域，我们将为您展示它的详细信息') // 用户提示
    handleClickToEditFeature(areaLayer, '区域') // 注册点击事件处理器
  }
}
/**
 * 处理多选结果中的选择
 * 当查询返回多个要素时，用户从列表中选择一个要素后的处理函数
 *
 * @param data - 用户选择的要素数据(景点/路线/区域)
 */
let multiSelectHandle = (data: SpotType | RoadType | AreaType) => {
  if (dataDrawerType === 'spot') {
    // 处理景点类型
    spotData.value = data as SpotType // 设置选中的景点数据
    // 查找并高亮显示对应的要素
    clickQueryResult?.features.forEach((feature) => {
      if (feature.attributes.FID === data.FID) {
        highlightFeature(spotLayer, feature)
      }
    })
  } else if (dataDrawerType === 'road') {
    // 处理路线类型
    roadData.value = data as RoadType // 设置选中的路线数据
    // 查找并高亮显示对应的要素
    clickQueryResult?.features.forEach((feature) => {
      if (feature.attributes.FID === data.FID) {
        highlightFeature(roadLayer, feature)
      }
    })
  } else if (dataDrawerType === 'area') {
    // 处理区域类型
    areaData.value = data as AreaType // 设置选中的区域数据
    // 查找并高亮显示对应的要素
    clickQueryResult?.features.forEach((feature) => {
      if (feature.attributes.FID === data.FID) {
        highlightFeature(areaLayer, feature)
      }
    })
  }

  // 关闭多选模式，显示详情抽屉
  multiSelect.value = false
  DetailDrawer.value = true
}

/**
 * 导航功能相关变量
 */
// 位置和路线图形
let userLocation: __esri.Point | null = null // 用户当前位置点
let userLocationGraphic: __esri.Graphic | null = null // 用户位置图形标记
let destinationSpot: Graphic | null = null // 目的地景点
const routeGraphics: __esri.Graphic[] = [] // 存储路线相关的所有图形

// 路线信息
const routeDistance = ref(0) // 路线总距离(米)
const routeTime = ref(0) // 路线预计时间(秒)
const routeInstructions = ref<string[]>([]) // 导航指令列表
const destinationName = ref('目的地') // 目的地名称
const showRouteDetails = ref(false) // 是否显示路线详情面板

/**
 * 导航状态控制变量
 */
const isNavigating = ref(false) // 是否正在导航中
const currentStepIndex = ref(0) // 当前导航步骤索引

/**
 * 导航到景点功能
 * 实现从用户选择的起点到目的地景点的路线规划
 * 流程：选择起点 -> 选择目的地 -> 计算路线 -> 显示导航指引
 */
const NavigateToSpot = async () => {
  // 清除之前的导航状态和图形
  highlightHandle.removeAll() // 清除高亮
  view.graphics.removeAll() // 清除地图上的图形
  routeGraphics.length = 0 // 清空路线图形数组
  userLocation = null // 重置用户位置
  userLocationGraphic = null // 重置用户位置图形
  destinationSpot = null // 重置目的地
  showRouteDetails.value = false // 隐藏路线详情面板
  isNavigating.value = false // 重置导航状态

  // 提示用户操作步骤
  Toast.info('请点击地图选择您的位置')

  // 移除之前可能存在的点击事件处理器
  if (clickHandler) {
    clickHandler.remove()
    clickHandler = null
  }

  // 添加新的点击事件处理器
  let isSelectingStart = true // 标记当前是否在选择起点
  clickHandler = view.on('click', async (event) => {
    // 获取点击位置
    const mapPoint = event.mapPoint.clone()

    if (isSelectingStart) {
      // 设置用户位置
      setUserLocation(mapPoint)
      isSelectingStart = false
      Toast.info('请点击景点作为目的地')
    } else {
      // 查询点击位置的景点
      const query = new Query()
      query.geometry = mapPoint
      query.distance = 3
      query.units = 'meters'
      query.spatialRelationship = 'intersects'
      query.returnGeometry = true
      query.outFields = ['*']

      try {
        const results = await spotLayer.queryFeatures(query)

        if (results.features.length === 0) {
          Toast.info('请点击景点位置')
          return
        }

        // 处理多个景点的情况
        if (results.features.length > 1) {
          clickQueryResult = results
          detailTitle = `该区域存在多个景点，请选择具体的一个景点`
          dataDrawerType = 'spot'
          multiSelectTableData.value = results.features.map((feature) => feature.attributes as SpotType)
          multiSelect.value = true

          // 添加多选回调处理
          const handleMultiSelect = (selectedSpot: SpotType | RoadType | AreaType) => {
            const selectedFeature = results.features.find((f) => f.attributes.FID === selectedSpot.FID)
            if (selectedFeature) {
              destinationSpot = selectedFeature
              calculateRoute(selectedFeature)
            }
            multiSelect.value = false
          }

          // 覆盖原有的多选处理函数
          multiSelectHandle = handleMultiSelect
          return
        }

        // 处理单个景点的情况
        destinationSpot = results.features[0]
        calculateRoute(destinationSpot)
      } catch (error) {
        console.error('导航错误:', error)
        Toast.error('导航计算失败')
      }
    }
  })
}

// 设置用户位置
function setUserLocation(point: __esri.Point) {
  // 清除之前的用户位置标记
  if (userLocationGraphic) {
    view.graphics.remove(userLocationGraphic)
  }

  // 保存用户位置
  userLocation = point

  // 创建用户位置标记
  const symbol = {
    type: 'simple-marker',
    style: 'circle',
    size: 12,
    color: [255, 0, 0], // 鲜红色(#FF0000)，不透明，用于突出显示用户当前位置
    outline: {
      color: [255, 255, 255], // 纯白色(#FFFFFF)边框，不透明，增强在各种底图上的可见性
      width: 2, // 较粗的边框宽度，提高可识别性
    },
  }

  userLocationGraphic = new Graphic({
    geometry: point,
    symbol: symbol as any,
  })

  view.graphics.add(userLocationGraphic)
  routeGraphics.push(userLocationGraphic)
}
// 计算路线
async function calculateRoute(destinationFeature: Graphic) {
  // 开始性能计时
  performanceTest.startTimer('routePlanning', {
    destination: destinationFeature.attributes.SpotName || '目的地景点'
  });

  if (!userLocation) {
    Toast.warning('请先选择您的位置')
    performanceTest.endTimer('routePlanning', { success: false, reason: 'noUserLocation' });
    return
  }

  try {
    // 清除之前的路线
    clearRoute()

    // 保存目的地名称
    destinationName.value = destinationFeature.attributes.SpotName || '景点'

    // 调用高德路径规划API
    const routeResult = await getGaoDeRoute(
      `${userLocation.longitude},${userLocation.latitude}`,
      `${(destinationFeature.geometry as Point).longitude},${(destinationFeature.geometry as Point).latitude}`
    )
    // 绘制路线
    if (routeResult && routeResult.route && routeResult.route.paths[0]) {
      const path = routeResult.route.paths[0]

      // 将路径点转换为二维数组
      const pathPoints = path.steps.flatMap((step) => {
        return step.polyline.split(';').map((point) => {
          const [lng, lat] = point.split(',').map(Number)
          return [lng, lat]
        })
      })

      // 创建路线图形
      const routeLine = new Graphic({
        geometry: new Polyline({
          paths: [pathPoints],
        }),
        symbol: new SimpleLineSymbol({
          color: [0, 122, 194, 0.8], // 亮蓝色(#007AC2)，透明度为0.8，用于导航路线，蓝色与红色景点形成鲜明对比
          width: 4, // 较粗的线宽，使路线在地图上清晰可见
        }),
      })

      view.graphics.add(routeLine)

      routeGraphics.push(routeLine)
      // 提取路线指引信息
      routeInstructions.value = path.steps.map((step) => step.instruction)

      // 设置路线距离和时间
      routeDistance.value = Number(path.distance)
      routeTime.value = Number(path.duration)

      // 显示路线详情卡片
      showRouteDetails.value = true

      // 高亮显示终点景点
      highlightFeature(spotLayer, destinationFeature)

      // 移除点击事件处理器
      if (clickHandler) {
        clickHandler.remove()
        clickHandler = null
      }

      // 记录性能数据 - 路线规划成功
      performanceTest.endTimer('routePlanning', {
        success: true,
        distance: routeDistance.value,
        duration: routeTime.value,
        stepsCount: path.steps.length
      });
    } else {
      Toast.error('无法获取路线信息')
      // 记录性能数据 - 路线规划失败
      performanceTest.endTimer('routePlanning', {
        success: false,
        reason: 'noRouteInfo'
      });
    }
  } catch (error) {
    console.error('路线规划失败', error)
    Toast.error('路线规划失败')

    // 记录性能数据 - 路线规划异常
    performanceTest.endTimer('routePlanning', {
      success: false,
      error: error instanceof Error ? error.message : String(error)
    });
  }
}

// 清空路线
function clearRoute() {
  // 清除临时图层中的所有图形
  if (tempGraphicLayer) {
    tempGraphicLayer.removeAll()
  }
  view.graphics.removeAll()
  // 重新添加用户位置标记（如果存在）
  if (userLocationGraphic && tempGraphicLayer) {
    tempGraphicLayer.add(userLocationGraphic)
  }

  // 清除路线图形数组中的路线，但保留用户位置标记
  const userLocationGraphicTemp = userLocationGraphic
  routeGraphics.length = 0
  if (userLocationGraphicTemp) {
    routeGraphics.push(userLocationGraphicTemp)
  }

  // 重置路线信息
  routeInstructions.value = []
  routeDistance.value = 0
  routeTime.value = 0
  showRouteDetails.value = false
  isNavigating.value = false
}

// 开始导航
function startNavigation() {
  if (routeInstructions.value.length === 0) {
    Toast.warning('请先规划路线')
    return
  }

  isNavigating.value = true
  currentStepIndex.value = 0

  Toast.success('导航已开始，请按照指引前往目的地')
}

/**
 * 切换位置跟踪状态
 * 使用Capacitor Geolocation API实现实时位置跟踪功能
 * 支持Web和移动平台，自动处理权限请求
 */
const toggleLocationTracking = async () => {
  if (!isTracking.value) {
    // 开始性能计时
    performanceTest.startTimer('locationTracking', { action: 'start' });

    // 开启位置跟踪
    try {
      // 检查当前平台，Web和移动平台处理方式不同
      const isPlatformWeb = Capacitor.getPlatform() === 'web'

      // 检查位置权限状态
      const permissionStatus = await Geolocation.checkPermissions()

      // 在移动平台上需要显式请求权限
      if (permissionStatus.location !== 'granted' && !isPlatformWeb) {
        await Geolocation.requestPermissions()
      }

      // 获取当前位置作为起始点
      const position = await Geolocation.getCurrentPosition({
        enableHighAccuracy: true, // 使用高精度定位
        timeout: 10000, // 超时时间10秒
        maximumAge: 0, // 不使用缓存位置
      },)

      // 更新跟踪状态
      isTracking.value = true

      // 将地图中心移动到当前位置
      view.goTo({
        target: new Point({
          longitude: position.coords.longitude,
          latitude: position.coords.latitude,
          spatialReference: view.spatialReference,
        }),
        zoom: 15, // 设置适当的缩放级别
      })

      // 启动持续位置监听
      watchId = await Geolocation.watchPosition(
        {
          enableHighAccuracy: true, // 使用高精度定位
          timeout: 1000, // 更新超时时间1秒
          maximumAge: 0, // 不使用缓存位置
        },
        (position) => {
          // 位置更新回调
          if (!position) return // 无效位置数据，直接返回

          // 创建当前位置点
          const currentLocation = new Point({
            longitude: position.coords.longitude,
            latitude: position.coords.latitude,
            spatialReference: view.spatialReference,
          })

          // 更新或创建位置图标
          if (locationGraphic) {
            // 已有图标，只更新位置
            locationGraphic.geometry = currentLocation
          } else {
            // 创建新的位置图标
            locationGraphic = new Graphic({
              geometry: currentLocation,
              symbol: {
                type: 'simple-marker',
                style: 'circle',
                color: [0, 123, 255], // 蓝色(#007BFF)，不透明，用于实时位置跟踪，与导航路线颜色协调
                size: 12, // 图标大小，足够大以便于用户识别
                outline: {
                  width: 2, // 较粗的边框宽度，增强可见性
                  color: [255, 255, 255], // 纯白色(#FFFFFF)边框，不透明，在各种底图上都能清晰显示
                },
              } as never,
            })
            // 添加到地图
            view.graphics.add(locationGraphic)
          }

          // 地图跟随位置移动
          view.goTo({
            target: currentLocation,
            zoom: view.zoom, // 保持当前缩放级别不变
          })
        }
      )

      // 提示用户
      Toast.success('已开启实时定位')

      // 记录性能数据 - 位置跟踪成功启动
      performanceTest.endTimer('locationTracking', {
        success: true,
        platform: Capacitor.getPlatform()
      });
    } catch (error) {
      // 处理错误
      console.error('定位错误:', error)
      isTracking.value = false

      // 记录性能数据 - 位置跟踪启动失败
      performanceTest.endTimer('locationTracking', {
        success: false,
        error: error instanceof Error ? error.message : String(error),
        platform: Capacitor.getPlatform()
      });
    }
  } else {
    // 开始性能计时
    performanceTest.startTimer('locationTracking', { action: 'stop' });

    // 关闭位置跟踪
    if (watchId) {
      // 停止位置监听
      await Geolocation.clearWatch({ id: watchId })
      watchId = null
    }

    if (locationGraphic) {
      // 移除位置图标
      view.graphics.remove(locationGraphic)
      locationGraphic = null
    }

    // 更新状态
    isTracking.value = false
    Toast.success('已关闭实时定位')

    // 记录性能数据 - 位置跟踪停止
    performanceTest.endTimer('locationTracking', {
      success: true,
      action: 'stop',
      platform: Capacitor.getPlatform()
    });
  }
}
const cancelDetailView = () => {
  DetailDrawer.value = false
}
// 控制面板展开状态
const expandedPanels = ref({
  spot: false,
  road: false,
  area: false,
  weather: false,
  spotType: false,
})

// 切换面板展开状态
const togglePanel = (panel: 'spot' | 'road' | 'area' | 'weather' | 'spotType') => {
  expandedPanels.value[panel] = !expandedPanels.value[panel]
}

/**
 * 按名称搜索景点/路线/区域
 * 同时在三个图层中搜索匹配的要素，并显示结果
 * 支持单个结果直接显示和多个结果让用户选择
 */
const searchByName = async () => {
  // 开始性能计时
  performanceTest.startTimer('searchByName', {
    keyword: searchText.value
  });

  // 验证搜索输入
  if (!searchText.value.trim()) {
    Toast.info('请输入搜索内容')
    performanceTest.endTimer('searchByName', {
      success: false,
      reason: 'emptyKeyword'
    });
    return
  }

  // 清除之前的高亮显示
  highlightHandle.removeAll()

  // 构建基础查询参数
  const query = new Query()
  query.returnGeometry = true // 返回几何信息
  query.outFields = ['*'] // 返回所有字段

  // 存储各图层的搜索结果
  const searchResults = {
    spots: [] as Graphic[], // 景点结果
    roads: [] as Graphic[], // 路线结果
    areas: [] as Graphic[], // 区域结果
  }

  try {
    // 1. 查询景点图层
    query.where = `SpotName LIKE '%${searchText.value}%'` // 模糊匹配景点名称
    const spotResults = await spotLayer.queryFeatures(query)
    searchResults.spots = spotResults.features

    // 2. 查询路线图层
    query.where = `RoadName LIKE '%${searchText.value}%'` // 模糊匹配路线名称
    const roadResults = await roadLayer.queryFeatures(query)
    searchResults.roads = roadResults.features

    // 3. 查询区域图层
    query.where = `AreaName LIKE '%${searchText.value}%'` // 模糊匹配区域名称
    const areaResults = await areaLayer.queryFeatures(query)
    searchResults.areas = areaResults.features

    // 合并所有图层的结果
    const allResults = [...searchResults.spots, ...searchResults.roads, ...searchResults.areas]

    // 处理无结果情况
    if (allResults.length === 0) {
      Toast.info('未找到匹配的景点/路线/区域')

      // 记录性能数据 - 搜索无结果
      performanceTest.endTimer('searchByName', {
        success: true,
        resultsCount: 0,
        keyword: searchText.value
      });
      return
    }

    // 处理单个结果情况
    if (allResults.length === 1) {
      // 只有一个结果，直接显示详情
      const result = allResults[0]
      const layer = result.layer as FeatureLayer

      // 高亮显示结果
      highlightFeature(layer, result)

      // 根据图层类型设置详情数据
      if (layer === spotLayer) {
        spotData.value = result.attributes as SpotType
        dataDrawerType = 'spot'
      } else if (layer === roadLayer) {
        roadData.value = result.attributes as RoadType
        dataDrawerType = 'road'
      } else if (layer === areaLayer) {
        areaData.value = result.attributes as AreaType
        dataDrawerType = 'area'
      }

      // 显示详情抽屉
      DetailDrawer.value = true

      // 记录性能数据 - 搜索单个结果
      performanceTest.endTimer('searchByName', {
        success: true,
        resultsCount: 1,
        resultType: layer === spotLayer ? 'spot' : (layer === roadLayer ? 'road' : 'area'),
        keyword: searchText.value
      });
    } else {
      // 处理多个结果情况
      // 创建结果集合
      clickQueryResult = new FeatureSet({
        features: allResults,
      })

      // 提取各类型的属性数据
      const spotResults = searchResults.spots.map((feature) => feature.attributes as SpotType)
      const roadResults = searchResults.roads.map((feature) => feature.attributes as RoadType)
      const areaResults = searchResults.areas.map((feature) => feature.attributes as AreaType)

      // 合并所有结果到多选表格数据中，添加类型标识
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error - 类型合并需要忽略类型检查
      multiSelectTableData.value = [
        ...spotResults.map((item) => ({ type: 'spot', ...item })), // 景点结果
        ...roadResults.map((item) => ({ type: 'road', ...item })), // 路线结果
        ...areaResults.map((item) => ({ type: 'area', ...item })), // 区域结果
      ]

      // 自定义多选处理函数
      multiSelectHandle = (selectedItem) => {
        // 根据选择项的属性判断类型并找到对应的图层和要素
        let selectedFeature: Graphic | undefined
        let selectedLayer: FeatureLayer

        if ('SpotName' in selectedItem) {
          // 处理景点类型
          selectedFeature = searchResults.spots.find((f) => f.attributes.FID === selectedItem.FID)
          selectedLayer = spotLayer
          spotData.value = selectedItem as SpotType
          dataDrawerType = 'spot'
        } else if ('RoadName' in selectedItem) {
          // 处理路线类型
          selectedFeature = searchResults.roads.find((f) => f.attributes.FID === selectedItem.FID)
          selectedLayer = roadLayer
          roadData.value = selectedItem as RoadType
          dataDrawerType = 'road'
        } else if ('AreaName' in selectedItem) {
          // 处理区域类型
          selectedFeature = searchResults.areas.find((f) => f.attributes.FID === selectedItem.FID)
          selectedLayer = areaLayer
          areaData.value = selectedItem as AreaType
          dataDrawerType = 'area'
        }

        // 高亮显示选中的要素
        if (selectedFeature && selectedLayer!) {
          highlightFeature(selectedLayer, selectedFeature)
        }

        // 关闭多选模式，显示详情
        multiSelect.value = false
        DetailDrawer.value = true
      }

      // 设置多选对话框标题
      detailTitle = `找到${allResults.length}个匹配结果，请选择一个查看详情`

      // 显示多选对话框
      multiSelect.value = true

      // 记录性能数据 - 搜索多个结果
      performanceTest.endTimer('searchByName', {
        success: true,
        resultsCount: allResults.length,
        spotsCount: searchResults.spots.length,
        roadsCount: searchResults.roads.length,
        areasCount: searchResults.areas.length,
        keyword: searchText.value
      });
    }
  } catch (error) {
    // 错误处理
    console.error('搜索错误:', error)
    Toast.error('搜索过程中发生错误')

    // 记录性能数据 - 搜索错误
    performanceTest.endTimer('searchByName', {
      success: false,
      error: error instanceof Error ? error.message : String(error),
      keyword: searchText.value
    });
  }
}

/**
 * 根据景点类型筛选景点
 * 支持按游玩、文化、度假、其他等类型筛选景点
 *
 * @param type - 景点类型
 */
const filterSpotsByType = async (type: string) => {
  // 设置当前选中的类型并显示筛选面板
  selectedSpotType.value = type
  showTypeFilter.value = true

  // 构建查询参数
  const query = new Query()
  query.returnGeometry = true // 返回几何信息
  query.outFields = ['*'] // 返回所有字段
  query.where = `1=1` // 查询所有景点，在前端进行筛选更灵活

  try {
    // 查询所有景点
    const results = await spotLayer.queryFeatures(query)

    // 在前端筛选指定类型的景点
    // 注意：对于未设置类型的景点，归类为"其他"
    filteredSpots.value = results.features
      .map((feature) => feature.attributes as SpotType)
      .filter((spot) => spot.spotType === type || (!spot.spotType && type === '其他'))

    // 处理无结果情况
    if (filteredSpots.value.length === 0) {
      Toast.info(`未找到${type}类型的景点`)
      showTypeFilter.value = false // 关闭筛选面板
    }
  } catch (error) {
    // 错误处理
    console.error('筛选错误:', error)
    Toast.error('筛选过程中发生错误')
    showTypeFilter.value = false // 关闭筛选面板
  }
}

/**
 * 查看筛选后的景点详情
 * 从筛选结果列表中选择景点后，查询完整信息并显示详情
 *
 * @param spot - 选中的景点数据
 */
const viewFilteredSpotDetail = async (spot: SpotType) => {
  // 构建精确查询参数
  const query = new Query()
  query.returnGeometry = true // 返回几何信息
  query.outFields = ['*'] // 返回所有字段
  query.where = `FID = ${spot.FID}` // 按对象ID精确查询

  try {
    // 查询景点完整信息
    const results = await spotLayer.queryFeatures(query)
    if (results.features.length > 0) {
      // 高亮显示选中的景点
      highlightFeature(spotLayer, results.features[0])

      // 设置景点数据并显示详情
      spotData.value = results.features[0].attributes as SpotType
      dataDrawerType = 'spot' // 设置数据类型为景点
      showTypeFilter.value = false // 关闭筛选面板
      DetailDrawer.value = true // 显示详情抽屉
    }
  } catch (error) {
    // 错误处理
    console.error('获取景点详情错误:', error)
    Toast.error('获取景点详情失败')
  }
}


/**
 * 性能测试相关变量和函数
 */
// 性能测试状态控制
const showPerformancePanel = ref(false) // 控制性能面板显示
const performanceReport = ref<Record<string, any>>({}) // 存储性能报告数据

/**
 * 生成并显示性能报告
 * 收集所有性能测试数据并显示在面板中
 */
const generatePerformanceReport = () => {
  // 获取性能测试报告
  performanceReport.value = performanceTest.generateReport()

  // 显示性能测试面板
  showPerformancePanel.value = true
}

/**
 * 清除性能记录
 * 重置所有性能测试数据
 */
const clearPerformanceRecords = () => {
  // 清除性能测试记录
  performanceTest.clearRecords()

  // 清空报告数据
  performanceReport.value = {}

  // 提示用户
  Toast.success('性能测试记录已清除')
}

//待dom元素完成后加入
onMounted(async () => {
  // 开始性能计时
  performanceTest.startTimer('mapInitialization');

  view.container = mapViewContainer.value!
  view.ui.add('functionPanel', 'top-right')
  view.ui.add('locateButton', 'bottom-right')

  // 获取天气数据
  const city = '370523' // 东营广饶的行政区划代码（adcode）
  const weather = await getAmapWeather(city)
  if (weather && weather.status === '1') {
    weatherData.value = weather.lives[0] // 实时天气数据
  } else {
    weatherError.value = '无法获取天气信息'
  }

  // 监听地图加载完成事件
  view.when(() => {
    performanceTest.endTimer('mapInitialization');
    console.log('地图性能报告:', performanceTest.generateReport());
  });

  // 监控资源加载性能
  setTimeout(() => {
    performanceTest.monitorResourceLoading();
  }, 5000); // 等待5秒后检查资源加载情况
})
</script>
<template>
  <ion-page>
    <div id="mapViewContainer" ref="mapViewContainer" class="mapView">
      <div id="functionPanel" class="function-panel">
        <!-- 天气信息 -->
        <div class="panel-item weather-info" v-if="weatherData">
          <div class="panel-header" @click="togglePanel('weather')">
            <ion-icon :icon="moonOutline"></ion-icon>
            <span>当前天气</span>
            <ion-icon :icon="chevronDownOutline" class="expand-icon"
              :class="{ rotated: expandedPanels.weather }"></ion-icon>
          </div>
          <div class="panel-content" v-show="expandedPanels.weather">
            <ion-item>
              <ion-label>
                <ion-icon :icon="moonOutline" class="ion-margin-end"></ion-icon>
                城市: {{ weatherData.city }}
              </ion-label>
            </ion-item>
            <ion-item>
              <ion-label>
                <ion-icon :icon="moonOutline" class="ion-margin-end"></ion-icon>
                温度: {{ weatherData.temperature }}°C
              </ion-label>
            </ion-item>
            <ion-item>
              <ion-label>
                <ion-icon :icon="moonOutline" class="ion-margin-end"></ion-icon>
                天气: {{ weatherData.weather }}
              </ion-label>
            </ion-item>
            <ion-item>
              <ion-label>
                <ion-icon :icon="moonOutline" class="ion-margin-end"></ion-icon>
                湿度: {{ weatherData.humidity }}%
              </ion-label>
            </ion-item>
          </div>
        </div>

        <!-- 景点管理面板 -->
        <div class="panel-item">
          <div class="panel-header" @click="togglePanel('spot')">
            <ion-icon :icon="locationOutline"></ion-icon>
            <span>景点</span>
            <ion-icon :icon="chevronDownOutline" class="expand-icon"
              :class="{ rotated: expandedPanels.spot }"></ion-icon>
          </div>
          <div class="panel-content" v-show="expandedPanels.spot">
            <ion-item button @click="searchScenic('spot')">
              <ion-icon :icon="eyeOutline" slot="start"></ion-icon>
              <ion-label>查看景点详情</ion-label>
            </ion-item>
          </div>
        </div>

        <!-- 路线管理面板 -->
        <div class="panel-item">
          <div class="panel-header" @click="togglePanel('road')">
            <ion-icon :icon="gitNetworkOutline"></ion-icon>
            <span>路线</span>
            <ion-icon :icon="chevronDownOutline" class="expand-icon"
              :class="{ rotated: expandedPanels.road }"></ion-icon>
          </div>
          <div class="panel-content" v-show="expandedPanels.road">
            <ion-item button @click="searchScenic('road')">
              <ion-icon :icon="eyeOutline" slot="start"></ion-icon>
              <ion-label>查看路线详情</ion-label>
            </ion-item>
          </div>
        </div>

        <!-- 区域管理面板 -->
        <div class="panel-item">
          <div class="panel-header" @click="togglePanel('area')">
            <ion-icon :icon="cropOutline"></ion-icon>
            <span>区域</span>
            <ion-icon :icon="chevronDownOutline" class="expand-icon"
              :class="{ rotated: expandedPanels.area }"></ion-icon>
          </div>
          <div class="panel-content" v-show="expandedPanels.area">
            <ion-item button @click="searchScenic('area')">
              <ion-icon :icon="eyeOutline" slot="start"></ion-icon>
              <ion-label>查看区域详情</ion-label>
            </ion-item>
          </div>
        </div>

        <!-- 景点类型筛选面板 -->
        <div class="panel-item">
          <div class="panel-header" @click="togglePanel('spotType')">
            <ion-icon :icon="filterOutline"></ion-icon>
            <span>景点类型攻略</span>
            <ion-icon :icon="chevronDownOutline" class="expand-icon"
              :class="{ rotated: expandedPanels.spotType }"></ion-icon>
          </div>
          <div class="panel-content" v-show="expandedPanels.spotType">
            <ion-item button v-for="type in spotTypes" :key="type" @click="filterSpotsByType(type)">
              <ion-icon :icon="eyeOutline" slot="start"></ion-icon>
              <ion-label>{{ type }}类景点</ion-label>
            </ion-item>
          </div>
        </div>

        <div class="panel-item">
          <div class="panel-header" @click="NavigateToSpot()">
            <ion-icon :icon="compassOutline"></ion-icon>
            <span>导航去景点</span>
          </div>
        </div>

        <!-- 搜索功能面板 -->
        <div class="panel-item">
          <div class="search-container">
            <ion-input placeholder="输入景点/路线/区域名称" v-model="searchText" class="search-input"></ion-input>
            <ion-button size="small" @click="searchByName()" class="search-button">查询</ion-button>
          </div>
        </div>
        <!-- 性能测试按钮容器 -->
        <div class="panel-item performance-button-container">
          <ion-button expand="block" size="small" @click="generatePerformanceReport" color="tertiary">
            <ion-icon :icon="speedometerOutline" slot="start"></ion-icon>
            性能测试报告
          </ion-button>
        </div>
      </div>

      <ion-button @click="toggleLocationTracking" id="locateButton" :color="isTracking ? 'danger' : 'primary'">
        <ion-icon :icon="locationOutline" slot="start"></ion-icon>
        {{ isTracking ? '关闭定位' : '开启定位' }}
      </ion-button>
    </div>

    <!-- 性能测试面板 -->
    <ion-modal :is-open="showPerformancePanel" @didDismiss="() => (showPerformancePanel = false)">
      <ion-header>
        <ion-toolbar>
          <ion-title>性能测试报告</ion-title>
          <ion-buttons slot="end">
            <ion-button @click="showPerformancePanel = false">
              <ion-icon :icon="closeOutline"></ion-icon>
            </ion-button>
          </ion-buttons>
        </ion-toolbar>
      </ion-header>

      <ion-content>
        <div class="performance-controls">
          <ion-button color="danger" size="small" @click="clearPerformanceRecords">
            清除性能记录
          </ion-button>
        </div>

        <div class="performance-table">
          <!-- 表头 -->
          <div class="table-header">
            <div class="table-cell" style="width: 30%">操作名称</div>
            <div class="table-cell" style="width: 14%">执行次数</div>
            <div class="table-cell" style="width: 14%">平均耗时(ms)</div>
            <div class="table-cell" style="width: 14%">最小耗时(ms)</div>
            <div class="table-cell" style="width: 14%">最大耗时(ms)</div>
            <div class="table-cell" style="width: 14%">最近执行(ms)</div>
          </div>

          <!-- 表格内容 -->
          <div class="table-row" v-for="(item, index) in Object.entries(performanceReport).map(([key, value]) => ({key, ...value}))" :key="index">
            <div class="table-cell" style="width: 30%">{{ item.key }}</div>
            <div class="table-cell" style="width: 14%">{{ item.count }}</div>
            <div class="table-cell" style="width: 14%">{{ item.average ? item.average.toFixed(2) : 0 }}</div>
            <div class="table-cell" style="width: 14%">{{ item.min ? item.min.toFixed(2) : 0 }}</div>
            <div class="table-cell" style="width: 14%">{{ item.max ? item.max.toFixed(2) : 0 }}</div>
            <div class="table-cell" style="width: 14%">{{ item.lastExecution ? item.lastExecution.toFixed(2) : 0 }}</div>
          </div>
        </div>

        <div class="performance-tips">
          <p><strong>性能测试说明：</strong></p>
          <ul>
            <li>mapInitialization: 地图初始化时间</li>
            <li>query景点/道路/区域: 查询要素的时间</li>
            <li>routePlanning: 路线规划时间</li>
            <li>locationTracking: 位置跟踪时间</li>
            <li>searchByName: 搜索功能响应时间</li>
          </ul>
          <p>注意：耗时过长的操作可能需要优化。一般来说，用户交互操作应在300ms内响应，以保证良好的用户体验。</p>
        </div>
      </ion-content>
    </ion-modal>
    <!-- 路线详情卡片 -->
    <div class="route-card" v-if="showRouteDetails">
      <div class="route-header">
        <h3>导航路线</h3>
        <ion-button class="close-btn" fill="clear" size="small" @click="showRouteDetails = false">
          <ion-icon :icon="closeOutline"></ion-icon>
        </ion-button>
      </div>

      <div class="route-summary">
        <div class="summary-item">
          <ion-icon :icon="locationOutline"></ion-icon>
          <span>{{ (routeDistance / 1000).toFixed(2) }}km</span>
        </div>
        <div class="summary-item">
          <ion-icon :icon="moonOutline"></ion-icon>
          <span>约{{ Math.ceil(routeTime / 60) }}分钟</span>
        </div>
      </div>

      <!-- 添加导航路线指引列表 -->
      <div class="route-instructions" v-if="routeInstructions.length > 0">
        <div class="instruction-title">导航指引</div>
        <div class="instructions-list">
          <div class="instruction-item" v-for="(instruction, index) in routeInstructions" :key="index">
            <div class="instruction-index">{{ index + 1 }}</div>
            <div class="instruction-text">{{ instruction }}</div>
          </div>
        </div>
      </div>

      <div class="card-actions">
        <ion-button color="primary" size="small" @click="startNavigation()" :disabled="isNavigating"> 开始导航 </ion-button>
        <ion-button color="danger" size="small" @click="clearRoute()"> 清空路线 </ion-button>
      </div>
    </div>

    <ion-modal :is-open="multiSelect">
      <ion-header>
        <ion-toolbar>
          <ion-title>{{ detailTitle }}</ion-title>
          <ion-buttons slot="end">
            <ion-button @click="multiSelect = false">
              <ion-icon :icon="closeOutline"></ion-icon>
            </ion-button>
          </ion-buttons>
        </ion-toolbar>
      </ion-header>

      <ion-content>
        <ion-list>
          <ion-item-divider>
            <ion-label>名称</ion-label>
            <ion-label slot="end">类型</ion-label>
            <ion-label slot="end">操作</ion-label>
          </ion-item-divider>

          <!-- 混合结果列表 -->
          <ion-item v-for="(item, index) in multiSelectTableData" :key="index">
            <!-- 景点 -->
            <ion-label v-if="'SpotName' in item">{{ (item as SpotType).SpotName }}</ion-label>
            <!-- 路线 -->
            <ion-label v-else-if="'RoadName' in item">{{ (item as RoadType).RoadName }}</ion-label>
            <!-- 区域 -->
            <ion-label v-else-if="'AreaName' in item">{{ (item as AreaType).AreaName }}</ion-label>

            <!-- 类型标签 -->
            <ion-note slot="end" color="medium">
              <span v-if="'SpotName' in item">景点</span>
              <span v-else-if="'RoadName' in item">路线</span>
              <span v-else-if="'AreaName' in item">区域</span>
            </ion-note>

            <ion-button slot="end" @click="multiSelectHandle(item)">查看</ion-button>
          </ion-item>
        </ion-list>
      </ion-content>
    </ion-modal>
    <!-- 景点类型筛选结果弹窗 -->
    <ion-modal :is-open="showTypeFilter" @didDismiss="() => (showTypeFilter = false)">
      <ion-header>
        <ion-toolbar>
          <ion-title>{{ selectedSpotType }}类型景点</ion-title>
          <ion-buttons slot="end">
            <ion-button @click="showTypeFilter = false">
              <ion-icon :icon="closeOutline"></ion-icon>
            </ion-button>
          </ion-buttons>
        </ion-toolbar>
      </ion-header>

      <ion-content>
        <ion-list>
          <ion-item-divider>
            <ion-label>景点名称</ion-label>
            <ion-label slot="end">操作</ion-label>
          </ion-item-divider>

          <ion-item v-for="(spot, index) in filteredSpots" :key="index">
            <ion-label>{{ spot.SpotName }}</ion-label>
            <ion-button slot="end" @click="viewFilteredSpotDetail(spot)">查看详情</ion-button>
          </ion-item>

          <ion-item v-if="filteredSpots.length === 0">
            <ion-label class="ion-text-center">未找到{{ selectedSpotType }}类型的景点</ion-label>
          </ion-item>
        </ion-list>
      </ion-content>
    </ion-modal>

    <ion-modal :is-open="DetailDrawer" @didDismiss="() => (DetailDrawer = false)">
      <!-- 景点详情 -->
      <ion-content v-if="dataDrawerType === 'spot'">
        <ion-card>
          <ion-card-header>
            <div class="header-container">
              <ion-card-title>景点详情</ion-card-title>
              <ion-button fill="clear" @click="cancelDetailView()">
                <ion-icon :icon="closeOutline"></ion-icon>
                关闭
              </ion-button>
            </div>
          </ion-card-header>

          <ion-card-content>
            <ion-list>
              <ion-item>
                <ion-label>
                  <ion-icon :icon="moonOutline" class="ion-margin-end"></ion-icon>
                  景点名称
                </ion-label>
                <ion-note slot="end">{{ spotData?.SpotName }}</ion-note>
              </ion-item>

              <ion-item v-if="spotData?.spotType">
                <ion-label>
                  <ion-icon :icon="filterOutline" class="ion-margin-end"></ion-icon>
                  景点类型
                </ion-label>
                <ion-note slot="end">{{ spotData?.spotType }}</ion-note>
              </ion-item>

              <ion-item v-if="spotData?.SpotIntroduction">
                <ion-label class="ion-text-wrap">
                  <ion-icon :icon="listOutline" class="ion-margin-end"></ion-icon>
                  景点详细描述
                  <p>{{ spotData?.SpotIntroduction }}</p>
                </ion-label>
              </ion-item>

              <ion-item v-if="spotData?.IntroduceImageBase64">
                <ion-label class="ion-text-wrap">
                  <ion-icon :icon="imageOutline" class="ion-margin-end"></ion-icon>
                  景点宣传图片
                </ion-label>
              </ion-item>
              <div class="ion-padding" v-if="spotData?.IntroduceImageBase64">
                <ion-img :src="spotData?.IntroduceImageBase64"></ion-img>
              </div>
            </ion-list>
          </ion-card-content>
        </ion-card>
      </ion-content>
      <ion-content v-if="dataDrawerType === 'road'">
        <ion-card>
          <ion-card-header>
            <div class="header-container">
              <ion-card-title>景点路线详情</ion-card-title>
              <ion-button fill="clear" @click="cancelDetailView()">
                <ion-icon :icon="closeOutline"></ion-icon>
                关闭
              </ion-button>
            </div>
          </ion-card-header>

          <ion-card-content>
            <ion-list>
              <ion-item>
                <ion-label>
                  <ion-icon :icon="moonOutline" class="ion-margin-end"></ion-icon>
                  景点路线名称
                </ion-label>
                <ion-note slot="end">{{ roadData?.RoadName }}</ion-note>
              </ion-item>

              <ion-item v-if="roadData?.RoadIntroduction">
                <ion-label class="ion-text-wrap">
                  <ion-icon :icon="listOutline" class="ion-margin-end"></ion-icon>
                  景点路线详细描述
                  <p>{{ roadData?.RoadIntroduction }}</p>
                </ion-label>
              </ion-item>

              <ion-item v-if="roadData?.IntroduceImageBase64">
                <ion-label class="ion-text-wrap">
                  <ion-icon :icon="imageOutline" class="ion-margin-end"></ion-icon>
                  景点宣传图片
                </ion-label>
              </ion-item>
              <div class="ion-padding" v-if="roadData?.IntroduceImageBase64">
                <ion-img :src="roadData?.IntroduceImageBase64"></ion-img>
              </div>
            </ion-list>
          </ion-card-content>
        </ion-card>
      </ion-content>
      <ion-content v-if="dataDrawerType === 'area'">
        <ion-card>
          <ion-card-header>
            <div class="header-container">
              <ion-card-title>景点区域详情</ion-card-title>
              <ion-button fill="clear" @click="cancelDetailView()">
                <ion-icon :icon="closeOutline"></ion-icon>
                关闭
              </ion-button>
            </div>
          </ion-card-header>

          <ion-card-content>
            <ion-list>
              <ion-item>
                <ion-label>
                  <ion-icon :icon="moonOutline" class="ion-margin-end"></ion-icon>
                  景点区域名称
                </ion-label>
                <ion-note slot="end">{{ areaData?.AreaName }}</ion-note>
              </ion-item>

              <ion-item v-if="areaData?.AreaIntroduction">
                <ion-label class="ion-text-wrap">
                  <ion-icon :icon="listOutline" class="ion-margin-end"></ion-icon>
                  景点区域详细描述
                  <p>{{ areaData?.AreaIntroduction }}</p>
                </ion-label>
              </ion-item>

              <ion-item v-if="areaData?.IntroduceImageBase64">
                <ion-label class="ion-text-wrap">
                  <ion-icon :icon="imageOutline" class="ion-margin-end"></ion-icon>
                  景点区域宣传图片
                </ion-label>
              </ion-item>
              <div class="ion-padding" v-if="areaData?.IntroduceImageBase64">
                <ion-img :src="areaData?.IntroduceImageBase64"></ion-img>
              </div>
            </ion-list>
          </ion-card-content>
        </ion-card>
      </ion-content>
    </ion-modal>
  </ion-page>
</template>
<style scoped>
.mapView {
  width: 100%;
  height: 100%;
  position: relative;
}

.function-panel {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.92);
  border-radius: 12px;
  box-shadow: 0 4px 15px 0 rgba(0, 0, 0, 0.15);
  padding: 5px;
  width: auto;
  min-width: 160px;
  max-width: 280px;
  backdrop-filter: blur(10px);
  z-index: 1000;
  border: 1px solid rgba(144, 202, 249, 0.5);
}

.panel-item {
  margin-bottom: 5px;
  border-bottom: 1px solid rgba(144, 202, 249, 0.2);
}

.panel-item:last-child {
  border-bottom: none;
}

.panel-header {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s;
  color: #2c3e50;
  font-weight: 500;
}

.panel-header:hover {
  background-color: rgba(66, 165, 245, 0.15);
  transform: translateX(2px);
}

.panel-header ion-icon {
  margin-right: 10px;
  color: #1976d2;
  font-size: 1.2em;
}

.panel-header span {
  flex: 1;
}

.expand-icon {
  transition: transform 0.3s;
  color: #64b5f6;
}

.expand-icon.rotated {
  transform: rotate(180deg);
}

.panel-content {
  padding-left: 10px;
  margin-bottom: 5px;
}

:deep(ion-item) {
  --background: transparent;
  --padding-start: 10px;
  --min-height: 40px;
  font-size: 0.95em;
  --color: #455a64;
}

:deep(ion-item:hover) {
  --background: rgba(66, 165, 245, 0.1);
  --color: #1976d2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .function-panel {
    max-width: 180px;
    font-size: 0.9em;
  }

  :deep(ion-item) {
    --min-height: 36px;
    font-size: 0.85em;
  }
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.weather-info {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  padding: 8px;
  margin-bottom: 10px;
  border-left: 4px solid #42a5f5;
}

.weather-info .panel-header {
  font-weight: bold;
  font-size: 1.1em;
  color: #0d47a1;
}

.weather-info .panel-content {
  padding-left: 16px;
}

.weather-info ion-item {
  --min-height: 32px;
  font-size: 0.9em;
}

/* 搜索框样式 */
.search-container {
  display: flex;
  padding: 10px;
  align-items: center;
  background: rgba(236, 239, 241, 0.5);
  border-radius: 8px;
  margin: 5px;
}

.search-input {
  flex: 1;
  --background: rgba(255, 255, 255, 0.9);
  --border-radius: 6px;
  --padding-start: 10px;
  --padding-end: 10px;
  font-size: 0.95em;
  margin-right: 6px;
  --box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.search-button {
  --padding-start: 10px;
  --padding-end: 10px;
  height: 38px;
  --background: #1976d2;
  --color: white;
  --border-radius: 6px;
  --box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 定位按钮样式 */
#locateButton {
  --border-radius: 50%;
  --padding-start: 12px;
  --padding-end: 12px;
  height: 50px;
  width: 50px;
  margin: 15px;
  --box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

/* 添加旅游风格的卡片样式 */
:deep(ion-card) {
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin: 16px;
  border-top: 4px solid #42a5f5;
}

:deep(ion-card-header) {
  background-color: rgba(236, 239, 241, 0.5);
}

:deep(ion-card-title) {
  color: #0d47a1;
  font-size: 1.3em;
  font-weight: 600;
}

:deep(ion-card-content) {
  padding: 16px;
}

:deep(ion-note) {
  font-size: 0.9em;
  color: #1976d2;
}

/* 模态框样式 */
:deep(ion-modal) {
  --border-radius: 16px;
  --box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
}

:deep(ion-toolbar) {
  --background: #1976d2;
  --color: white;
}

:deep(ion-title) {
  font-size: 1.2em;
  font-weight: 500;
}

:deep(ion-item-divider) {
  --background: rgba(236, 239, 241, 0.8);
  --color: #0d47a1;
  font-weight: 500;
}

/* 景点类型筛选按钮样式 */
.panel-content ion-item[button] {
  --background-hover: rgba(66, 165, 245, 0.15);
  border-left: 3px solid transparent;
  transition: all 0.2s;
}

.panel-content ion-item[button]:hover {
  border-left: 3px solid #42a5f5;
}

/* 导航按钮特殊样式 */
.panel-item .panel-header:has(ion-icon[icon='compass-outline']) {
  background-color: rgba(66, 165, 245, 0.15);
  color: #0d47a1;
  font-weight: 600;
  border-left: 3px solid #1976d2;
}

.panel-item .panel-header:has(ion-icon[icon='compass-outline']):hover {
  background-color: rgba(66, 165, 245, 0.25);
}

/* 图片容器样式 */
.ion-padding:has(ion-img) {
  padding: 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  margin: 10px 0;
}

:deep(ion-img) {
  border-radius: 8px;
  transition: transform 0.3s;
}

:deep(ion-img:hover) {
  transform: scale(1.02);
}

/* 路线详情卡片 */
.route-card {
  position: absolute;
  bottom: 20px;
  right: 20px;
  width: 350px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
  overflow: hidden;
  padding: 15px;
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.route-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: #0d47a1;
}

.route-summary {
  display: flex;
  margin-bottom: 15px;
}

.summary-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  color: #1976d2;
}

.summary-item ion-icon {
  margin-right: 5px;
}

.step-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #0d47a1;
}

.step-detail {
  font-size: 13px;
  color: #666;
  margin-bottom: 15px;
}

.instructions-list {
  margin-top: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.instruction-item {
  display: flex;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

.instruction-index {
  width: 24px;
  height: 24px;
  background-color: #1976d2;
  color: #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  flex-shrink: 0;
  font-size: 12px;
}

.instruction-text {
  flex: 1;
  line-height: 1.5;
  font-size: 14px;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

/* 导航提示 */
.navigation-hint {
  position: absolute;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  max-width: 500px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  z-index: 10;
}

.hint-content {
  margin-bottom: 10px;
}

.current-instruction {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #0d47a1;
}

.next-step {
  font-size: 13px;
  color: #666;
  margin-top: 5px;
}

/* 性能测试面板样式 */
.performance-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 1000;
  overflow-y: auto;
  padding: 20px;
  color: white;
}

.performance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.performance-title {
  font-size: 20px;
  font-weight: bold;
}

.performance-close {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
}

.performance-content {
  margin-bottom: 20px;
}

.performance-section {
  margin-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #4fc3f7;
}

.performance-item {
  margin-bottom: 8px;
}

.item-name {
  font-weight: bold;
  margin-right: 10px;
}

.item-value {
  color: #81c784;
}

.performance-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

#performanceButton {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 10;
}
/* 性能测试相关样式 */
.performance-controls {
  margin: 15px;
  display: flex;
  justify-content: flex-end;
}

.performance-table {
  margin: 0 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.table-row:nth-child(even) {
  background-color: #fafafa;
}

.table-cell {
  padding: 12px 8px;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.table-header .table-cell {
  font-weight: bold;
}

.performance-tips {
  margin: 20px 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 14px;
}

.performance-tips ul {
  margin: 10px 0;
  padding-left: 20px;
}

.performance-tips li {
  margin-bottom: 5px;
}

.performance-button-container {
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
}
</style>
